package com.zby.charity.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zby.charity.common.BaseResponse;
import com.zby.charity.common.ErrorCode;
import com.zby.charity.common.ResultUtils;
import com.zby.charity.entity.CommentsEntity;
import com.zby.charity.entity.PostsEntity;
import com.zby.charity.entity.UserEntity;
import com.zby.charity.entity.vo.AboutCommentsVo;
import com.zby.charity.entity.vo.CommentsVo;
import com.zby.charity.exception.BusinessException;
import com.zby.charity.service.CommentsService;
import com.zby.charity.service.PostsService;
import com.zby.charity.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zby
 * @email 2069189112@qq.com
 * @date 2025-01-16 18:25:18
 */
@RestController
@RequestMapping("charity/comments")
public class CommentsController {
    @Autowired
    private UserService userService;
    @Autowired
    private CommentsService commentsService;
    @Autowired
    private PostsService postsService;

    @PostMapping("/addComments")
    public BaseResponse<Boolean> addComment(@RequestBody CommentsEntity commentsEntity, HttpServletRequest request) {
        UserEntity loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "用户未登录");
        }
        if (commentsEntity == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "评论实体不能为空");
        }
        if (commentsEntity.getParentId() == null || commentsEntity.getParentId() < 0)
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "父评论ID不能为空");
        if (!commentsEntity.getUid().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "评论用户id与当前用户id不一致");
        }
        boolean result = commentsService.addComments(commentsEntity);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "评论失败");
        }
        return ResultUtils.success(true);
    }
    @GetMapping("/deleteComments")
    public BaseResponse<Boolean> deleteComments(@RequestParam("id") int id) {
        boolean result = commentsService.removeById(id);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除失败");
        }
        return ResultUtils.success(true);
    }
    @GetMapping("/listComment")
    public BaseResponse<List<CommentsVo>> list(@RequestParam("pid") int pid) {
        QueryWrapper<CommentsEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid", pid);
        List<CommentsEntity> list = commentsService.list(queryWrapper);
        List<CommentsVo> commentsVoList = list.stream().map(commentsEntity -> {
            CommentsVo commentsVo = new CommentsVo();
            Integer uid = commentsEntity.getUid();
            if (uid == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR);
            }
            Integer replyId = commentsEntity.getReplyId();
            if (!replyId.equals(0)) {
                UserEntity byId = userService.getById(commentsEntity.getReplyId());
                String name = byId.getName();
                commentsEntity.setReplyname(name);
            }
            BeanUtils.copyProperties(commentsEntity, commentsVo);
            commentsVo.setUsername(userService.getById(uid).getName());
            return commentsVo;
        }).collect(Collectors.toList());

        Map<Integer, CommentsVo> commentsMap = commentsVoList.stream()
                .collect(Collectors.toMap(CommentsVo::getId, commentsVo -> commentsVo));


        List<CommentsVo> rootComments = new ArrayList<>();

        for (CommentsVo commentsVo : commentsVoList) {
            Integer parentId = commentsVo.getParentId();
            if (parentId == null || parentId == 0) {
                // 如果parentId为null或0，则为根评论
                rootComments.add(commentsVo);
            } else {
                // 否则，找到其父评论并添加到父评论的children列表中
                CommentsVo parentComment = commentsMap.get(parentId);
                if (parentComment == null)
                    throw new BusinessException(ErrorCode.PARAMS_ERROR);
                if (parentComment.getChildren() == null) {
                    parentComment.setChildren(new ArrayList<>());
                }
                parentComment.getChildren().add(commentsVo);
            }
        }

        return ResultUtils.success(rootComments);
    }

    @GetMapping("/listCommentByUid")
    public BaseResponse<List<AboutCommentsVo>> listCommentByUid(@RequestParam("uid") int uid) {
        //对id进行判断是否小于0
        if (uid <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<CommentsEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid", uid);
        List<CommentsEntity> list = commentsService.list(queryWrapper);
        List<AboutCommentsVo> aboutCommentsVoList = list.stream()
                .sorted(Comparator.comparing(CommentsEntity::getCreateAt).reversed())
                .map(commentsEntity -> {
                    AboutCommentsVo aboutCommentsVo = new AboutCommentsVo();
                    BeanUtils.copyProperties(commentsEntity, aboutCommentsVo);
                    String name = userService.getById(commentsEntity.getUid()).getName();
                    aboutCommentsVo.setUsername(name);
                    PostsEntity byId = postsService.getById(commentsEntity.getPid());
                    aboutCommentsVo.setPostTitle(byId.getTitle());
                    return aboutCommentsVo;
                }).collect(Collectors.toList());
        return ResultUtils.success(aboutCommentsVoList);
    }


    @GetMapping("/listCommentByUserId")
    public BaseResponse<List<AboutCommentsVo>> listCommentByUserId(@RequestParam("authorId") int authorId) {
        // 参数校验
        if (authorId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "Invalid authorId");
        }

        // 查询该作者的所有帖子
        QueryWrapper<PostsEntity> postsQueryWrapper = new QueryWrapper<>();
        postsQueryWrapper.eq("author_id", authorId);
        List<PostsEntity> postsList = postsService.list(postsQueryWrapper);

        // 如果没有帖子，直接返回空列表
        if (postsList.isEmpty()) {
            return ResultUtils.success(Collections.emptyList());
        }

        // 提前将帖子 ID 和帖子标题映射为 Map，减少后续查询次数
        Map<Integer, String> postIdToTitleMap = postsList.stream()
                .collect(Collectors.toMap(PostsEntity::getId, PostsEntity::getTitle));

        // 查询这些帖子的所有评论
        QueryWrapper<CommentsEntity> commentsQueryWrapper = new QueryWrapper<>();
        commentsQueryWrapper.in("pid", postIdToTitleMap.keySet());
        List<CommentsEntity> commentsList = commentsService.list(commentsQueryWrapper);

        // 如果没有评论，直接返回空列表
        if (commentsList.isEmpty()) {
            return ResultUtils.success(Collections.emptyList());
        }

        // 提前查询所有评论对应的用户信息
        Set<Integer> userIds = commentsList.stream().map(CommentsEntity::getUid).collect(Collectors.toSet());
        Map<Integer, UserEntity> userMap = userService.listByIds(userIds).stream()
                .collect(Collectors.toMap(UserEntity::getId, user -> user));

        // 转换为 AboutCommentsVo 并设置帖子标题和用户信息
        List<AboutCommentsVo> aboutCommentsVoList = commentsList.stream()
                .sorted(Comparator.comparing(CommentsEntity::getCreateAt).reversed())
                .map(commentsEntity -> {
                    AboutCommentsVo aboutCommentsVo = new AboutCommentsVo();
                    BeanUtils.copyProperties(commentsEntity, aboutCommentsVo);
                    aboutCommentsVo.setPostTitle(postIdToTitleMap.get(commentsEntity.getPid()));
                    UserEntity user = userMap.get(commentsEntity.getUid());
                    if (user != null) {
                        aboutCommentsVo.setUsername(user.getName());
                        aboutCommentsVo.setAvatarUrl(user.getAvatarUrl());
                    }
                    return aboutCommentsVo;
                })
                .collect(Collectors.toList());

        return ResultUtils.success(aboutCommentsVoList);
    }
}
